package com.rabbit.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class ReduceConsumer implements ChannelAwareMessageListener {
    //这个对应的是与“Reduce”业务对应的消费者，有几个不同的业务对应几个不同的消费者，
    // 当然如果消息体里有区分不同业务的数据就无需这样做了，看具体业务场景可以灵活应对。
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            byte[] body = message.getBody();
            String s = new String(body, "utf-8");
            Map map = JSONObject.parseObject(s, Map.class);
            System.out.println("Reduce线程: " + Thread.currentThread().getName());
            System.out.println("Reduce业务消费方消费了数据：" + map);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            e.printStackTrace();
        }
    }
}
